<template>
  <div style="padding:20px" >
    <Form :labelWidth="110" class="title-suffix" mode="twocolumn">
      <FormItem label="输入数据类型">
        <Radio v-model="sourceType" :datas="sourceOptions"/>
      </FormItem>
      <div style="display: inline-block;width: 50%;color:#b5b5b5;padding-left:110px">
        提示：该工具为快速模版工具，其他更多在线工具可前往<a href="https://tool.oschina.net/" target="_blank">OSChina 在线工具</a>。该工具模板引擎使用<a href="https://aui.github.io/art-template/zh-cn/docs/index.html" target="_blank">art-template</a>。内置变量有i和it,分别表数据下标和数据项值。自动循环数据进行渲染。
      </div>
      <FormItem label="源数据">
        <Textarea v-model="source" style="min-height: 200px;resize:none;"></Textarea>
      </FormItem>
      <FormItem label="输入模板">
        <Textarea v-model="template" style="min-height: 200px;resize:none;"></Textarea>
      </FormItem>
      <div style="width: 50%;text-align: right;padding-bottom:20px;">
        <FileInput accept=".txt,.json" @change="onFileSelect">
          <Button icon="jeicon-file">选择文件</Button>
        </FileInput>
        <Space/>
        <Button icon="jeicon-trash" @click="trashInput">清除输入</Button>
      </div>
      <div style="width: 50%;text-align: right;padding-bottom:20px;">
        <Button icon="jeicon-play" @click="generate">执行</Button>
      </div>
      <FormItem label="输出" single>
        <Textarea v-model="output" style="min-height: 200px;resize: vertical;"></Textarea>
      </FormItem>
    </Form>
  </div>
</template>
<script>
  import {ajax,format} from 'framework'
  import {modal} from 'heyui'
  import '../js/art.js'
  template.defaults.imports.json=function(data){
    return JSON.stringify(data);
  }
  template.defaults.imports.format=function(data,fmt){
    return format(data,fmt);
  }

  function tpl(str, data) {
    var str_fun = "var p=[];with(obj){p.push('" + str.replace(/[\r\n\t]/g, " ").replace(/\${([^}]+)}/g, "ʚ);p.push($1);p.push(ʚ").replace(/'/g, "\\'").replace(/ʚ/g, "'") + "');}return p.join('');";
    var fn = new Function("obj", str_fun);
    return data ? fn(data) : fn;
  }

  export default{
    name:'GenTool',
    data(){
      return {
        sourceType:"1",
        source:'10',
        sourceOptions:{
          1:'次数',
          2:'\',\'分割文本',
          3:'换行分割文本',
          4:'json数组',
          5:'sql',
          6:'模型列表'
        },
        template:'{{if i%2==0}}<div id="test_{{3*i}}">{{it}}</div>\n{{/if}}',
        output:''
      }
    },
    mounted(){
      if(localStorage._tmp_gen_template){
        this.template=localStorage._tmp_gen_template
      }
    },
    methods:{
      trashInput(){
        this.source=''
      },
      onFileSelect(file){
        const reader = new FileReader()
        reader.readAsText(file,'utf8') // input.files[0]为第一个文件
        reader.onload = ()=>{
          this.source=reader.result  // reader.result为获取结果
        }
      },
      generate(){
        if(!this.template){
          return
        }
        if(!this.source){
          return;
        }
        let s='';
        let temp=''
        try{
          temp=template.compile(this.template)//tpl(this.template)
        }catch(e){
          modal({Message:e})
          return;
        }
        localStorage._tmp_gen_template=this.template;
        switch (this.sourceType){
          case "1":
            let count=Number(this.source);

            for(let i=1;i<count+1;i++){
              s+=temp({i:i,it:i})
            }
            this.output=s;
            break
          case "2":
            let dt=this.source.split(",");
            for(let i=0;i<dt.length;i++){
              s+=temp({i:i,it:dt[i]})
            }
            this.output=s;
            break
          case "3":
            let lines=this.source.split("\n");
            for(let i=0;i<lines.length;i++){
              let line=lines[i].split(",");
              s+=temp({i:i,it:line})
            }
            this.output=s;
            break
          case "4":
            let json=JSON.parse(this.source)
            for(let i=0;i<json.length;i++){
              s+=temp({i:i,it:json[i]})
            }
            this.output=s;
            break
          case "5":
            this.output="";
            if(this.source)
            ajax.post('dev/sql',{sql:this.source}).then(r=>{
              let json=r.data
              for(let i=0;i<json.length;i++){
                s+=temp({i:i,it:json[i]})
              }
              this.output=s;
            })
                break
          case "6":
            let id=this.source;
            ajax.get("dev/detail",{id:id}).then(r=>{
              let cols=r.data.columns;
              for(let i=0;i<cols.length;i++){
                s+=temp({i:i,it:cols[i]})
              }
              this.output=s;
            })
        }
      }
    }
  }
</script>
